﻿using System;
using System.Web;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;

namespace ExampleWebRole
{
    public class Global : HttpApplication
    {
        private void CreateSilverlightPolicy()
        {
            var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            var blobs = account.CreateCloudBlobClient();
            blobs.GetContainerReference("$root").CreateIfNotExist();
            blobs.GetContainerReference("$root").SetPermissions(
                new BlobContainerPermissions
                {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                });
            var blob = blobs.GetBlobReference("clientaccesspolicy.xml");
            blob.Properties.ContentType = "text/xml";
            blob.UploadText(@"<?xml version=""1.0"" encoding=""utf-8""?>
                    <access-policy>
                      <cross-domain-access>
                        <policy>
                          <allow-from http-methods=""*"" http-request-headers=""*"">
                            <domain uri=""*"" />
                            <domain uri=""http://*"" />
                          </allow-from>
                          <grant-to>
                            <resource path=""/"" include-subpaths=""true"" />
                          </grant-to>
                        </policy>
                      </cross-domain-access>
                    </access-policy>");
        }

        void SetPubliFilesBlobContainerPermissions(CloudBlobContainer blobContainer)
        {
            // Setup the permissions on the container to be public
            var permissions = new BlobContainerPermissions
            {
                PublicAccess = BlobContainerPublicAccessType.Container
            };

            blobContainer.SetPermissions(permissions);
        }

        void CreatePublicFilesBlobContainer()
        {
            // Setup the connection to Windows Azure Storage
            var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            var blobClient = storageAccount.CreateCloudBlobClient();

            // Get and create the container
            var blobContainer = blobClient.GetContainerReference("publicfiles");
            if (blobContainer.CreateIfNotExist()) SetPubliFilesBlobContainerPermissions(blobContainer);
        }

        void SetupCloudStorageAccountConfigurationSettingPublisher()
        {
            CloudStorageAccount.SetConfigurationSettingPublisher(
                    (configName, configSettingPublisher) =>
                    {
                        var connectionString =
                            RoleEnvironment.GetConfigurationSettingValue(configName);
                        configSettingPublisher(connectionString);
                    }
                );
        }

        void Application_Start(object sender, EventArgs e)
        {
            SetupCloudStorageAccountConfigurationSettingPublisher();
            CreateSilverlightPolicy();
            CreatePublicFilesBlobContainer();
        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs

        }

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.

        }

    }
}
